const { src, dest, parallel, series } = require("gulp");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const concat = require("gulp-concat");
const gulpif = require("gulp-if");
const rev = require("gulp-rev");
const minifyCSS = require("gulp-minify-css");
const filter = require("gulp-filter");
const inject = require("gulp-inject");
const htmlMin = require("gulp-htmlmin");
const revCollector = require("gulp-rev-collector");
const del = require("delete");
const browserSync = require("browser-sync").create();
const gulpWatch = require("gulp-watch");

const formal = "http://res-adv-jl.th11.cn/ad/assets/"; // cdn 地址
const local = ""; // 本地调试
let cdn = formal;

const ifInitFileFunc = res => file => {
  const ans = file.basename === "init.js";
  return res ? ans : !ans;
};

function buildJs() {
  const noInitFileFilter = filter(ifInitFileFunc(false));

  return src("src/js/*.js")
    .pipe(babel())
    .pipe(uglify())
    .pipe(gulpif(ifInitFileFunc(true), dest("temp/")))
    .pipe(noInitFileFilter)
    .pipe(src("src/js/lib/*.js"))
    .pipe(concat("vendor.js", { newLine: "" }))
    .pipe(rev())
    .pipe(dest("dist/"))
    .pipe(rev.manifest())
    .pipe(dest("temp/js/"));
}

function buildCSS() {
  return src("src/css/*.css")
    .pipe(minifyCSS())
    .pipe(concat("fun.min.css", { newLine: "" }))
    .pipe(rev())
    .pipe(dest("dist/"))
    .pipe(rev.manifest())
    .pipe(dest("temp/css/"));
}

function buildHtml() {
  const minOptions = {
    removeComments: true, // 清除HTML注释
    collapseWhitespace: true, // 压缩HTML
    collapseBooleanAttributes: true, // 省略布尔属性的值 <input checked="true"/> ==> <input />
    removeEmptyAttributes: true, // 删除所有空格作属性值 <input id="" /> ==> <input />
    removeScriptTypeAttributes: true, // 删除<script>的type="text/javascript"
    removeStyleLinkTypeAttributes: true, // 删除<style>和<link>的type="text/css"
    minifyJS: true, // 压缩页面JS
    minifyCSS: true // 压缩页面CSS
  };

  return src(["temp/**/*.json", "index.html"])
    .pipe(
      revCollector({
        dirReplacements: {
          "cdn/": cdn
        }
      })
    )
    .pipe(
      inject(src("temp/init*"), {
        starttag: "<!-- inject:FileContent:{{ext}} -->",
        endtag: "<!-- endinject -->",
        transform: (_, file) =>
          "<script>" + file.contents.toString("utf8") + "</script>"
      })
    )
    .pipe(htmlMin(minOptions))
    .pipe(dest("dist/"));
}

function beforeBuild(cb) {
  del(["dist", "temp"], cb);
}

function afterBuild(cb) {
  del(["temp"], cb);
}

const build = series(
  beforeBuild,
  parallel(buildJs, buildCSS),
  buildHtml,
  afterBuild
);

async function server() {
  cdn = local;
  await browserSync.init({
    server: {
      baseDir: ["./dist/", "./"]
    }
  });
}

function watch() {
  cdn = local;
  gulpWatch(
    ["./index.html", "src/**/*.js", "src/**/*.css"],
    series(build, browserSync.reload)
  );
}

exports.watch = watch;
exports.dev = series(server, watch);
exports.clean = beforeBuild;
exports.default = build;
